import XLSXStyle from "xlsx-style";

/**
 * 文件流转换
 */
const s2ab = (s) => {
    if (typeof ArrayBuffer !== "undefined") {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) {
            view[i] = s.charCodeAt(i) & 0xff;
        }
        return buf;
    } else {
        const buf = new Array(s.length);
        for (let i = 0; i !== s.length; ++i) {
            buf[i] = s.charCodeAt(i) & 0xff;
        }
        return buf;
    }
}

// blob转换方法
export function sheetToBlob(sheet, sheetName) {
    //工作簿名称
    let sheetNameS = sheetName || "sheet1";
    let workbook = {
        SheetNames: [sheetNameS],
        Sheets: {},
    };
    // 生成excel的配置项
    workbook.Sheets[sheetNameS] = sheet;
    let wo_pts = {
        bookType: 'xlsx', //文件的类型
        bookSST: true, //提高文件生成的速度
        type: 'binary',
        cellStyles: true,
    };
    let wb_out = XLSXStyle.write(workbook, wo_pts);
    return new Blob([s2ab(wb_out)], {type: "application/octet-stream;charset=utf-8"});
}

/**
 * 文件下载方法
 */
export function downLoadExcel(obj, filename) {
    let link = document.createElement("a");
    link.download = filename;
    link.href = URL.createObjectURL(obj);
    link.click();
    URL.revokeObjectURL(obj);
}

export default {
    sheetToBlob,
    downLoadExcel
};